package gee

import (
	"strings"
)

type node struct {
	pattern  string //待匹配路由，请求的完整路径
	part     string //前缀树节点
	children []*node
	isWild   bool
}

//第一个匹配成功的节点用于插入
func (n *node) matchChild(part string) *node {
	for _, child := range n.children {
		if child.part == part || child.isWild {
			return child
		}
	}
	return nil
}

//所有匹配成功的节点用于查找
func (n *node) matchChildren(part string) []*node {
	nodes := make([]*node, 0)
	for _, child := range n.children {
		if child.part == part || child.isWild {
			nodes = append(nodes, child)
		}
	}
	return nodes
}

//插入节点，寻找出第一个匹配的结果
func (n *node) insert(pattern string, parts []string, height int) {
	if len(parts) == height {
		n.pattern = pattern
		return
	}
	part := parts[height]
	child := n.matchChild(part)
	if child == nil {
		child = &node{part: part, isWild: part[0] == ':' || part[0] == '*'}
		//fmt.Println(*child)
		n.children = append(n.children, child)
	}
	child.insert(pattern, parts, height+1)
}

//查找给定路由寻找正确节点
func (n *node) search(parts []string, height int) *node {
	if len(parts) == height || strings.HasPrefix(n.part, "*") {
		if n.pattern == "" {
			return nil
		}
		//fmt.Println(n)
		return n
	}

	part := parts[height]
	//fmt.Println(1,part)
	children := n.matchChildren(part)
	//fmt.Printf("%+v",children)
	for _, child := range children {
		//fmt.Println(child.part)
		result := child.search(parts, height+1)
		if result != nil {
			return result
		}
	}
	return nil
}
